package com.study_security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study_security.domain.ResponseResult;
import com.study_security.dto.MemberDTO;
import com.study_security.dto.ProjectDTO;
import com.study_security.dto.TaskAiDTO;
import com.study_security.dto.TaskDTO;
import com.study_security.entity.Task;
import com.study_security.mapper.TaskMapper;
import com.study_security.mapper.UserMapper;
import com.study_security.service.ProjectService;
import com.study_security.service.SmsService;
import com.study_security.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProjectService projectService;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private SmsService smsService;
    @Override
    public List<TaskDTO> getTasksByProjectName(String projectName) {
        return taskMapper.selectTasksByProjectName(projectName);
    }
    @Override
    public List<TaskDTO> getTasksByProjectId(Long projectId) {
        return taskMapper.selectTasksByProjectId(projectId);
    }

    @Override
    public List<ProjectDTO> selectUserProjects(Long userId) {
        return taskMapper.selectUserProjects(userId);
    }

    @Override
    public Task getTaskById(Long taskId) {
        return taskMapper.getByTaskId(taskId);
    }

    @Override
        public boolean addTask(Task task) {
            int result = taskMapper.insertTask(task);
            return result > 0;
        }

    @Override
    public boolean updateTaskStatus(Long taskId) {
        int result = taskMapper.updateTaskStatus(taskId);
        return result > 0;
    }

    @Override
    public List<MemberDTO> getProjectMembers(Long projectId) {
        return taskMapper.selectProjectMembers(projectId);
    }

    @Override
    public boolean deleteTask(Long taskId) {
        int result = taskMapper.deleteTask(taskId);
        return result > 0;
    }

    @Override
    public boolean taskIdUserIdExisits(Long taskId, Long userId) {
        return taskMapper.countByTaskIdUserId(taskId,userId)==0;
    }

    @Override
    public boolean updateTask(Task task) {
        return taskMapper.updateTask(task) > 0;
    }



    @Override
    public List<TaskDTO> getTasksByMemberId(Long memberId) {
        return taskMapper.selectTasksByMemberId(memberId);
    }




    @Override
    public ResponseResult notifyProjectMembers(Long userId) {
        try {
            // 步骤1：获取当前用户负责的所有项目
            List<ProjectDTO> projects = projectService.getUserProjects(userId);
            if (projects == null || projects.isEmpty()) {
                return new ResponseResult(200, "用户没有负责的项目，未发送通知。");
            }

            // 步骤2：收集所有项目下任务的成员ID
            Set<Long> memberIds = new HashSet<>();
            for (ProjectDTO project : projects) {
                Long projectId = project.getProjectId();
                List<TaskDTO> tasks = this.getTasksByProjectId(projectId);
                if (tasks != null) {
                    for (TaskDTO task : tasks) {
                        if (task.getMemberId() != null) {
                            memberIds.add(task.getMemberId());
                        }
                    }
                }
            }

            if (memberIds.isEmpty()) {
                return new ResponseResult(200, "项目下没有任务成员，未发送通知。");
            }

            // 步骤3：记录已发送的电话号码，避免重复发送
            Set<String> sentPhoneNumbers = new HashSet<>();

            // 步骤4：根据成员ID获取手机号并发送短信通知
            for (Long memberId : memberIds) {
                String phoneNumber = userMapper.getPhoneNumberByUserId(memberId);
                // 过滤掉 null 或者空字符串的手机号
                if (phoneNumber != null && !phoneNumber.trim().isEmpty()) {
                    // 如果手机号已经发送过，则跳过
                    if (sentPhoneNumbers.contains(phoneNumber)) {
                        continue;
                    }

                    // 通知内容
                    String messageContent = "您的任务距离截止时间不足两天，请及时处理。";

                    // 调用通知短信发送
                    ResponseResult smsResult = smsService.sendNotificationByPhone(phoneNumber, messageContent);
                    if (smsResult.getCode() == 200) {
                        // 发送成功后记录已发送的电话号码
                        sentPhoneNumbers.add(phoneNumber);
                    } else {
                        // 推荐使用日志记录异常
                        System.out.println("通知发送失败，用户ID: " + memberId + ", 手机号: " + phoneNumber + ", 错误: " + smsResult.getMsg());
                    }
                } else {
                    // 推荐使用日志记录异常
                    System.out.println("用户ID: " + memberId + " 没有绑定有效的手机号。");
                }
            }

            return new ResponseResult(200, "通知已发送。");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, "通知发送失败：" + e.getMessage());
        }
    }



    @Override
    public List<TaskAiDTO> getTaskDetailsByTaskName(String taskName, Long memberId) {
        return taskMapper.selectTaskDetailsByTaskName(taskName, memberId);
    }

}
